<?php

namespace app\api\controller;

use app\common\model\GoodsCategory;
use app\common\util\MyException;
use hg\apidoc\annotation as Apidoc;
use think\facade\Db;
use think\facade\View;

/**
 * @Apidoc\Title("购物车")
 */
class CartApi extends Base
{
    /**
     * @Apidoc\Title("添加购物车")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/AddCart")
     * @Apidoc\Header(ref="auth")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Param("goods_id",type="int",require=true,default="1",desc="商品id")
     * @Apidoc\Param("goods_num",type="int",require=true,default="1",desc="商品数量")
     */
    function add_cart()
    {
        $goods_id = input("goods_id/d"); // 商品id
        $item_id = input("item_id/d"); // 规格表id
        $goods_num = input("goods_num/d");// 商品数量
        if (empty($goods_id)) {
            throw new MyException('请选择要购买的商品');
        }
        if (empty($goods_num)) {
            throw new MyException('购买商品数量不能为0');
        }
        $good = Db::name('goods')->where('goods_id=' . $goods_id . ' and is_on_sale=1')->find();
        if (empty($good) || $good['goods_type']!=2) {
            throw new MyException('商品不存在或者已下架');
        }
        //如果没有升级 就不允许加入购物车
        if ($this->user['level']==1){
            throw new MyException('请升级后在购买此商品');
        }
        $map['user_id'] = $this->user_id;
        $map['goods_id'] = $goods_id;
        $map['goods_sn'] = $good['goods_sn'];
        $map['goods_name'] = $good['goods_name'];
        if ($item_id){
            $item=Db::name('spec_goods_price')->where('item_id',$item_id)->find();
            $map['item_id']=$item_id;
            $map['item_name']=$item['key_name'];
            $map['goods_price']=$item['price'];
        }else{
            $map['goods_price']=$good['goods_price'];
        }
        $map['goods_num'] = $goods_num;
        $map['add_time'] = time();
        $where['user_id'] = $this->user_id;
        $where['goods_id'] = $goods_id;
        $cart = Db::name('cart')->where($where)->find();
        if ($cart) {
            $res = Db::name('cart')->where($where)->inc('goods_num', $goods_num)->update();
        } else {
            $res = Db::name('cart')->insert($map);
        }
        if ($res) {
            throw new MyException('加入购物车成功',200);
        } else {
            throw new MyException('加入购物车失败');
        }
    }
    /**
     * @Apidoc\Title("购物车列表")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/CartList")
     * @Apidoc\Header(ref="auth")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     */
    public function cart_list()
    {
        //获取该用户购物车所有内容
        $cartlist = Db::name('cart')
            ->where('user_id', $this->user_id)
            ->withoutField("user_id,goods_sn,add_time")
            ->order('id desc')
            ->select()->toArray();
        if ($cartlist) {
            $list=[];
            foreach ($cartlist as $cart) {
                $good=Db::name('goods')->where('goods_id='.$cart['goods_id'].' and is_on_sale=1')->find();
                $item=1;
                if ($cart['item_id']){
                    $item=Db::name('spec_goods_price')->where('item_id='.$cart['item_id'])->find();
                }
                if (empty($good) || empty($item) || $good['goods_type']!=2){//清除被删除的商品
                    Db::name('cart')->where('id',$cart['id'])->delete();
                }else{
                    if (is_array($item)){
                        $cart['max']=$item['store_count'];
                        $img=$item['spec_img'];
                    }else{
                        $cart['max']=$good['store_count'];
                    }
                    $cart['goods_img']= $img ? SITE_URL.$img: SITE_URL.$good['goods_img'];
                    $cart['disabled']= 0;
                    $list[] = $cart;
                }
            }
            $data['cartlist'] = $list;
            throw new MyException('获取成功',200,$data);
        }
        $file = "goods_id,goods_img,goods_price,goods_name,market_price,goods_type";
        $goods = Db::name('goods')->where('is_on_sale=1 and is_recommend=1')
            ->field($file)
            ->order('sort asc,goods_id asc')
            ->page(1, 20)
            ->select()->toArray();
        if ($goods) {
            foreach ($goods as $key => $val) {
                $val['goods_img'] = $val['goods_img'] ? SITE_URL . $val['goods_img'] : SITE_URL . '/static/images/not_adv.png';
                $goods[$key] = $val;
            }
        }
        $data['goods'] = $goods;
        $data['cartlist'] = [];
        throw new MyException('获取成功',200,$data);
    }

    /**
     * @Apidoc\Title("修改购物车商品数量")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/EditNum")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("id",type="int",require=true,default="",desc="修改数量的商品的购物车id")
     * @Apidoc\Param("goods_id",type="int",require=true,default="",desc="修改数量的商品的id")
     * @Apidoc\Param("num",type="int",require=true,default="",desc="要修改的数量")
     */
    public function edit_num()
    {
        $cart_id = input('id/d');
        $goods_num = input('num/d', 1);
        if (empty($goods_num)) {
            throw new MyException('购买商品数量不能为0');
        }
        $goods_id = input('goods_id/d');
        $goods = Db::name('goods')->where('goods_id', $goods_id)->find();
        if (!$goods || $goods['is_on_sale']==0){
            throw new MyException('商品不存在或已下架');
        }
        $stock = Db::name('goods')->where('goods_id', $goods_id)->value('store_count');
        if ($goods_num > $stock) {
            throw new MyException('购买商品数量不能大于库存');
        }
        $result = Db::name('cart')->where('id', $cart_id)->update(['goods_num' => $goods_num,'selected' => 1]);
        if ($result != false) {
            throw new MyException('修改成功',200);
        } else {
            throw new MyException('修改失败');
        }
    }
    /**
     * @Apidoc\Title("修改购物车商品选中状态")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/EditSel")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Param("id",type="int",default="1",desc="修改状态的购物车id")
     * @Apidoc\Param("selected",type="int",require=true,default="1",desc="要修改成的状态")
     */
    public function edit_sel()
    {
        $cart_id = input('id/d');
        $select = input('selected/d');
        if (empty($cart_id)) {
            $result = Db::name('cart')->where('user_id', $this->user_id)->update(['selected' => $select]);
        } else {
            $res = Db::name('cart')->find($cart_id);
            if (!$res) {
                throw new MyException('该商品不存在');
            }
            $result = Db::name('cart')->where('id', $cart_id)->update(['selected' => $select]);
        }
        if ($result) {
            throw new MyException('修改成功',200);
        } else {
            throw new MyException('修改失败');
        }
    }

    /**
     * @Apidoc\Title("删除购物车商品")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/DelCart")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("ids",type="string",require=true,default="1,2",desc="删除的商品的购物车id")
     */
    public function del_cart()
    {
        $cart_ids = input('ids');
        if (empty($cart_ids)) {
            throw new MyException('提交参数有误');
        }
        $result = Db::name('cart')->whereIn('id', $cart_ids)->delete();
        if ($result != false) {
            throw new MyException('删除成功',200);
        } else {
            throw new MyException('删除失败');
        }
    }

    /**
     * @Apidoc\Title("购物车商品移至收藏夹")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/MoveCart")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("ids",type="string",require=true,default="1,2",desc="购物车id")
     */
    public function move_to_collect()
    {
        $cart_ids = input('ids');
        if (empty($cart_ids)) {
            throw new MyException('提交参数有误');
        }
        $list=Db::name('cart')->whereIn('id', $cart_ids)->select();
        if (empty($list)){
            throw new MyException('提交数据为空');
        }
        foreach ($list as $val){
            $collect = Db::name('goods_collect')->where('goods_id=' . $val['goods_id'] . ' and user_id=' . $this->user_id)->find();
            if (empty($collect)){
                $map['user_id'] = $this->user_id;
                $map['goods_id'] = $val['goods_id'];
                $map['add_time'] = time();
                Db::name('goods_collect')->insert($map);
            }
        }
        $result = Db::name('cart')->whereIn('id', $cart_ids)->delete();
        if ($result != false) {
            throw new MyException('操作成功',200);
        } else {
            throw new MyException('操作失败');
        }
    }
}
